#include "udphome.h"
#include "ui_home.h"

#include <QUdpSocket>

HOME::HOME(QWidget *parent) :
    QWidget(parent),

    ui(new Ui::HOME)
{
    ui->setupUi(this);

    my_win_1 = new QLabel(ui->frame_3);
    QPixmap img_1(":/background/background/2001.jpg");

    my_win_1->setPixmap(img_1);
    my_win_1->setGeometry(ui->frame_3->rect()); // 填满整个窗口
    my_win_1->setScaledContents(true);  // 自动拉伸适配窗口大小
    my_win_1->lower();                  // 将背景设置到最底层


      udpSocket = new QUdpSocket(this);
      // 绑定端口，监听所有地址上的数据
      if (udpSocket->bind(QHostAddress("192.168.137.1"), 8004)) {
          qDebug() << "UDP端口 8004";
      } else {
          qDebug() << "UDP 绑定失败";
          return;
      }

    connect(udpSocket,&QUdpSocket::readyRead,this,&HOME::readPendingDatagrams);

}

HOME::~HOME()
{
    delete udp_server;
    delete ui;

}




void HOME::on_pushButton_clicked()
{
    AmapWeather  *Weather = new AmapWeather;
    Weather->GetResponse("430104");
    connect(Weather,&AmapWeather::send_Weather_data,this,&HOME::get_weather);

}

void HOME::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);            // 调用基类的 resizeEvent 方法
    my_win_1->setGeometry(this->rect());        // 根据窗口大小调整背景 QLabel 的尺寸
    ui->label_video->setGeometry(this->rect());

}

void HOME::readPendingDatagrams()
{
    // 循环读取所有可用数据包
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        QHostAddress sender;
        quint16 senderPort;

        // 接收数据包
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        ui->label_video->setAlignment(Qt::AlignCenter);

        // 将QByteArray转换为QImage
        QImage image;
        if (image.loadFromData(datagram)) {
            // 将QImage转换为QPixmap并设置到QLabel上
            QLabel label;
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label_video->setPixmap(pixmap);
            ui->label_video->show();
            qDebug() << "load image from data.";
        } else {
            // 如果图片加载失败，输出错误信息
            qDebug() << "Failed to load image from data.";
        }

      //  qDebug() << "Home Received data:" << datagram;
        qDebug() << "From:" << sender.toString() << ":" << senderPort;
    }
}



